public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double result = 0;
int len1 = nums1.length;
int len2 = nums2.length;
int mid = (int)Math.ceil((len1+ len2)/2.0);
int mergeLen = mid+1;
int[] mergeArray = new int[mergeLen];
int k = 0,i = 0,j = 0;
for(; k < mergeLen && (i<len1 && j<len2);){
mergeArray[k++] = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++] ;
}
if(i ==len1){
while(k< mergeLen&&j<len2){
mergeArray[k++] = nums2[j++];
}
}
if(j ==len2){
while(k< mergeLen&&i<len1){
mergeArray[k++] = nums1[i++];
}
}
result = mergeArray[mid-1];
int sum = len1+len2;
if(sum%2 == 0){
int resultBack = mergeArray[mid];
result = (result+resultBack)/2.0;
}
return result;
}
}
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
return findTheMedian(nums1,nums2);
}
private double findTheMedian(int num1[] ,int num2[]) {
int totoal = num1.length + num2.length;
int k = totoal/2 ;
if(totoal % 2 == 0){
double result = findKthElement(k, num1, num2, 0, 0) + findKthElement(k+1, num1, num2, 0, 0);
return result/2.0;
}else {
return findKthElement(k+1, num1, num2, 0, 0);
}
}
private double findKthElement(int k, int num1[] ,int num2[],int start1,int start2){
if(start1 >= num1.length){
return num2[start2+k-1];
}
if(start2 >= num2.length){
return num1[start1+k-1];
}
if(1 == k){
return Math.min(num1[start1], num2[start2]);
}
int halfK = k/2 - 1;
int halfKOfnum1 = start1 + halfK;
int halfKOfnum2 = start2 + halfK;
* !!!重要防止越界,当越界后,取最大值
* 越界意味着本数组元素不够,则不够的元素都应从另一个数组中获取;
* 之前另一数组取得halfk个元素均是合法的;
*/
int V1 = halfKOfnum1 < num1.length ? num1[halfKOfnum1] : Integer.MAX_VALUE;
int V2 = halfKOfnum2 < num2.length ? num2[halfKOfnum2] : Integer.MAX_VALUE;
int V2 = num2[halfKOfnum2];*/
if (V1 < V2) {
return findKthElement(k-k/2, num1, num2, halfKOfnum1+1, start2);
}else {
return findKthElement(k-k/2, num1, num2, start1, halfKOfnum2+1);
}
}
}